package com.yhm.NIO.ByteBuffer读写;

import java.nio.ByteBuffer;

public class ByteBuffer读写 {

  public static void main(String[] args) {

    ByteBuffer byteBuffer = ByteBuffer.allocate(4);//4个字节的byteBuffer 缓冲区

    System.out.println("第一步：ByteBuffer缓冲区信息：capacity=" + byteBuffer.capacity() + ",position=" + byteBuffer.position() + ",limit=" + byteBuffer.limit()
            + ",isDirect=" + byteBuffer.isDirect());
    byteBuffer.put((byte) 1);
    byteBuffer.put((byte) 2);
    byteBuffer.put((byte) 3);
    byteBuffer.put((byte) 4);

    byteBuffer.flip();//切换到读模式
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());


    System.out.println("第二步：ByteBuffer缓冲区信息：capacity=" + byteBuffer.capacity() + ",position=" + byteBuffer.position() + ",limit=" + byteBuffer.limit()
            + ",isDirect=" + byteBuffer.isDirect());

    byteBuffer.compact();//将已经读过的数据清除
    byteBuffer.put((byte) 5);//自动切换到写模式
    byteBuffer.put((byte) 6);
    byteBuffer.put((byte) 7);

    System.out.println("第三步：ByteBuffer缓冲区信息：capacity=" + byteBuffer.capacity() + ",position=" + byteBuffer.position() + ",limit=" + byteBuffer.limit()
            + ",isDirect=" + byteBuffer.isDirect());


    byteBuffer.flip();//切换到读模式
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());
    System.out.println("ByteBuffer缓冲区读取"+ byteBuffer.get());



  }
}
